var http = require('http'),
    util = require('util'),
    formidable = require('formidable');
var url = require("url");
var queryString = require("querystring");

function start(route, ctrlMap) {
    function onRequest(req, resp) {
        console.log("method=" + req.method + "!");
        var ctrlName = url.parse(req.url).pathname;
        var httpEnv = {};
        httpEnv.resp = resp;
        httpEnv.getParams = queryString.parse(url.parse(req.url).query);
        httpEnv.postParams = null;
        httpEnv.postFiles = null;
        if ("POST" == req.method) {
        	//这两个数组分别放什么信息
            files = [];
            fields = [];
            //新建一个formidable.IncomingForm对象
            var form = new formidable.IncomingForm();
            //文件的写入地址
            form.uploadDir = "d:/learn/";
            form
            //流中有字符串的话，将其键，值放入同一个数组，再将这个数组放进fields数组
              .on('field', function(field, value) {
                console.log(field, value);
                fields.push([field, value]);
              })
              //流中有文件的话，将流文件写入文件的写入地址form.uploadDir中，
              //并将文件名和文件地址放组成一个数组，再将这个数组放进file数组中
              .on('file', function(field, file) {
                console.log(field, file);
                files.push([field, file]);
              })
              .on('end', function() {
                console.log('-> upload done');
                
                httpEnv.postParams = {};
                var i = 0;
                for (i=0; i
                    httpEnv.postParams[fields[i][0]] = fields[i][1];
                }
                httpEnv.postFiles = {};
                for (i=0; i
                    httpEnv.postFiles[files[i][0]] = files[i][1];
                }
                
                
                route(httpEnv, ctrlMap, ctrlName);
              });
            form.parse(req);
        } else {
            route(httpEnv, ctrlMap, ctrlName);
        }
    }

    http.createServer(onRequest).listen(8089);

    console.log('listening on http://localhost:'+8089+'/');
}